package com.itheima.Security;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * <h3>health94_pareant</h3>
 * <p></p>
 *
 * @author : hhw
 * @date : 2020-03-30 21:42
 **/
@Component("securityUserService")
public class SecurityUserService implements UserDetailsService {
    @com.alibaba.dubbo.config.annotation.Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("我进来啦");
        //查询数据库的用户和权限并返回
        User user = userService.queryUser(username);

        List<GrantedAuthority> list = new LinkedList<>();
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), list);
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode1 = bCryptPasswordEncoder.encode("1234");
        String encode2 = bCryptPasswordEncoder.encode("1234");
        System.out.println(encode1);
        System.out.println(encode2);

        //使用明文密码和加密后的密码进行匹配
        System.out.println(bCryptPasswordEncoder.matches("1234","$2a$10$CPHqqqibhTbpQMDVqSs5BesCkFHywLd12NkwT8Cdwl4qKHGG3UfK6"));
        System.out.println(bCryptPasswordEncoder.matches("1234",encode1));

    }

}
